var webp=require('webp-converter');
var fs = require("fs");
var path = require("path");

var file_arr = [];

//path--路径
//dir --文件夹
var arg_path = '';
var arg_dir = '';
var len = 10;

exports.publish = function(_path,_dir) 
{
	console.log(_path);
	console.log(_dir);
	arg_path = _path;
	arg_dir = _dir;

	_read(_path + '/' + _dir);
	console.log(file_arr.length);
	next();
}

function next()
{
	if(file_arr.length > 0)
	{
		// len--;
		// if(len <= 0)
		// {
		// 	return;
		// }
		let p = file_arr.pop();
		// console.log(file_arr);
		// console.log(p);
	 	let src_img = p;
	 	let dist_img = p + '.webp';
	 	// console.log('src_img',src_img);
	 	// console.log('dist_img',dist_img);

	  	webp.cwebp(src_img,dist_img,"-q 75",function(status)
	  	{
	  		next();
	  	});
	}
}

//遍历文件夹，将png、jpg的路径存在一个数组里
function _read(src)
{
	let paths = fs.readdirSync(src);
	paths.forEach(function(_path)
	{
		let _src = path.join(src,_path);
		let stats = fs.statSync(_src);
		
		if (stats.isDirectory())
		{
			_read(_src);
		}
		else if(stats.isFile())
		{
			let ext = path.extname(_src);
			//console.log(ext);
			if((ext == '.png' || ext == '.jpg'))
			{
				file_arr.push(_src);
			}
		}
	})
}
